import hmac
import hashlib
import base64
import time
import json
import urllib.parse
import requests
from flask import Flask, request, jsonify

app = Flask(__name__)

class gl0906_dingtalk_notifier:
    def __init__(self, wb_url, secret, req_data):
        self.wb_url = wb_url
        self.secret = secret
        self.req_data = req_data

    def generate_sign(self):
        timestamp = str(round(time.time() * 1000))
        secret_enc = self.secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, self.secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        signature = base64.b64encode(hmac_code)
        signature = urllib.parse.quote_plus(signature)
        return timestamp, signature

    def prase_message(self):
        project = self.req_data.get('project', {})
        commits = self.req_data.get('commits', [])
        
        if not commits:
            return jsonify({'status': 'no commits'})

        project_name = project.get('name', 'Unknown Project')
        repository_url = project.get('web_url', 'Unknown URL')
        event_name = self.req_data.get('event_name', 'Unknown Event')
        ref_name = self.req_data.get('ref', 'Unknown ref')
        
        commit_messages = []
        for commit in commits:
            message = commit.get('message', 'No message')
            author = commit.get('author', {}).get('name', 'Unknown Author')
            timestamp = commit.get('timestamp', 'Unknown Timestamp')
            url = commit.get('url', 'Unknown URL')
            commit_messages.append(f"- **[{message}]({url})** by **{author}** at **{timestamp}**")

        commit_messages_str = "\n".join(commit_messages)
        self.sndmsgs = f"### Project: [{project_name}]({repository_url})\n\n**Event Name:** {event_name}\n\n**Ref Name:** {ref_name}\n\n**Commit Message:**\n{commit_messages_str}\n\n"

    def send_message(self):
        timestamp, signature = self.generate_sign()
        headers = {'Content-Type': 'application/json'}
        webhook_url = f'{self.wb_url}&timestamp={timestamp}&sign={signature}'

        payload = {
            "msgtype": "markdown",
            "markdown": {
                "title": "GitLab Commit Notification",
                "text": self.sndmsgs
            },
            "at": {
                "isAtAll": True
            }
        }

        response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))
        return response.status_code, response.text

DINGTALK_WEBHOOK_BSW_URL = 'https://oapi.dingtalk.com/robot/send?access_token=c94e45532723c32358a83ac3e2b0776b160e43a26c5721960d41ae9c3d171065'
DINGTALK_BSW_SECRET = 'SECbabdb590cdf9c9740de02d57cd817f11df41fd74eec676b98acffb1cf2657803'

DINGTALK_WEBHOOK_BSW2ASW_URL = 'https://oapi.dingtalk.com/robot/send?access_token=83879f6b70fb858e7d0df7e3a91e6f516e10dd57bc654f0f3b7004d6cb09ea89'
DINGTALK_BSW2ASW_SECRET = 'SEC33cf73bcf344a4d549525dd078bc48395e95cba56e048dbcadd4de44426226ca'

@app.route('/fbcm-pro/webhook', methods=['POST'])

def webhook():
    data = request.json
    project = data.get('project', {})
    project_name = project.get('name', 'Unknown Project')
    if 'bsw2asw' == project_name or 'asw2bsw' == project_name:
        notifier = gl0906_dingtalk_notifier(DINGTALK_WEBHOOK_BSW2ASW_URL, DINGTALK_BSW2ASW_SECRET, data)
    elif 'Deepway_FBCM_Project' == project_name:
        notifier = gl0906_dingtalk_notifier(DINGTALK_WEBHOOK_BSW_URL, DINGTALK_BSW_SECRET, data)
    else:
        return jsonify({'status': 'failed', 'error': "gl0906 webhook error"})
    notifier.prase_message()
    status_code, response_text = notifier.send_message()
    if status_code == 200:
        return jsonify({'status': 'success'})
    else:
        return jsonify({'status': 'failed', 'error': response_text})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

